<?php

namespace app\member\service;

use app\member\model\Tests;

class TestService
{

    public function listAll(){
        try{
            $db = new Tests();
            $data = $db->where("is_delete",0)->select();
            $res = AjaxReturn(0,'',$data);
            return $res;
        }catch (\Throwable $ex){
            return AjaxReturn(-1, '操作失败,错误信息:' . $ex->getMessage());
        }
    }

    /**
     * Notes:分页查询
     * User: ZHY
     * DateTime: 2023/7/5 21:02
     * @param $page
     * @param $limit
     * @param $where
     * @return array
     */
    public function list($page = 1, $limit = 10, $where = [])
    {
        try {
            array_push($where, ['is_delete', '=', 0]);
            $offset = ($page - 1) * $limit;
            $db = new Tests();
            $li = $db->
            where($where)->
            limit($offset, $limit)->
            order("id")->
            select();
            $count = $db->where($where)->count();
            return AjaxReturn(0, "", $li, $count);
        } catch (\Throwable $ex) {
            return AjaxReturn(-1, '操作失败,错误信息:' . $ex->getMessage());
        }
    }

    /**
     * Notes:添加
     */
    public function add($data)
    {
        try {
            $db = new Tests();
            $f = $db->where("test_name",$data["test_name"])->
                where("is_delete",0)->find();
            if($f){
                return AjaxReturn(-1,"试卷名称已存在");
            }

            $res = $db->insert($data);
            if ($res) {
                return AjaxReturn(0, '添加成功');
            } else {
                return AjaxReturn(-1, '添加失败');
            }
        } catch (\Throwable $ex) {
            return AjaxReturn(-1, '操作失败,错误信息:' . $ex->getMessage());
        }
    }

    public function softdelete($ids)
    {
        try {
            $db = new Tests();
            $res = $db->where('id', 'in', $ids)->update(['is_delete' => 1]);
            if ($res == count($ids)) {
                return AjaxReturn(0, '删除成功');
            } else {
                return AjaxReturn(-1, '删除失败');
            }
        } catch (\Throwable $ex) {
            return AjaxReturn(-1, '操作失败,错误信息:' . $ex->getMessage());
        }
    }

    public function edit($data)
    {
        try {
            $db = new Tests();
            $f = $db->where("test_name",$data['test_name'])->where('is_delete',0)
                ->where('id','<>',$data['id'])->find();
            if($f){
                return AjaxReturn(-1, '试卷名称冲突');
            }
            $db->update($data);
            return AjaxReturn(0, '操作成功');
        } catch (\Throwable $ex) {
            return AjaxReturn(-1, '操作失败,错误信息:' . $ex->getMessage());
        }
    }
}